/**
 * Created by XQ on 2015/8/4.
 */

$(function () {
    $("#running").bind("query", function () {
        $(this).attr("init", true);
        loadInterview('running', 2);
    });
    $("#open").bind("query", function () {
        $(this).attr("init", true);
        loadInterview('open', 1);
    });
    $("#closed").bind("query", function () {
        $(this).attr("init", true);
        loadInterview('closed', 3, false);
    });
    $("#job_open").bind("query", function () {
        $(this).attr("init", true);
        loadJob('job_open', 1, false);
    });
    $("#job_closed").bind("query", function () {
        $(this).attr("init", true);
        loadJob('job_closed', 0, false);
    });
    $("#myEnterprise").bind("query", function () {
        $(this).attr("init", true);
        loadEnterprise(1);
    });

    $("#enterprise_form").submit(function(){

        var tagList = [];
        $(".tag.checked").each(function(index){

            if(index > 7) return;
            tagList.push($(this).html().replace("#", "&"));
        });

        if(tagList.length < 9) {
            var tmpStr = $("#enterprise_exTag").val();
            if (tmpStr) {
                var tmpList = tmpStr.split(" ");
                for(var i= 0, len=tmpList.length; i<len; i+=1){

                    if(tmpList[i].trim()){
                        tagList.push(tmpList[i]);
                    }
                    if(tagList.length >= 8) break;
                }
            }
        }
        $("#enterprise_tag").val(tagList.join("#"));
    });

    //用户注册成功后展示企业信息界面，方便用户补充
    var vi = Utils.getUrlParam("vi");
    if (vi == "enterprise") {
        showType('info_item', 'enterprise_list_div', 'enterprise', 'myEnterprise');
    } else {
        showType('info_item', 'interview_list_div', 'interview', 'running');
    }
})

function initTag(userTag){

    var $tagWrap = $(".tag_wrap"),
        defaultTag = ["五险一金", "16薪", "年底双薪"],
        tagAll = defaultTag.concat(),
        userTagList = [],
        selected = [],
        $tagList = [];

    if(userTag) {
        userTagList = userTag.split("#");
    }

    for(var i= 0, len=userTagList.length; i<len; i+=1){
        for(var j= 0, len2=tagAll.length; j<len2; j+=1){
            if(userTagList[i] == tagAll[j] ){
                selected.push(j);
                break;
            }
        }
        if(j==len2){
            selected.push(tagAll.length);
            tagAll.push(userTagList[i]);
        }
    }

    $tagWrap.html();
    for(var i= 0, len=tagAll.length; i<len; i+=1){

        var $tag = $("<span />").addClass("tag").html(tagAll[i]);

        $tag.bind("click", function(){
            if($(this).hasClass("checked")){
                $(this).removeClass("checked");
            } else {
                if($(".tag.checked").length >= 8){
                    alert("最多选择8个标签");
                } else {
                    $(this).addClass("checked");
                }
            }
        });
        $tagList.push($tag)
        $tagWrap.append($tag);
    }

    for(var i= 0, len=selected.length; i<len; i+=1){
        $tagList[selected[i]].addClass("checked");
    }
}

function loadInterview(type, status, isSendResult) {
    var $search = QSearch.init(wp.config.baseUrl + "/rest/interview/grant/hr");
    var $footer = QFooter.init("#" + type + "_footer", function (pageNum) {
        $search.setPageNum(pageNum);
        $search.doSearch();
    });
    var enterLabel = "进入群面";
    if (status == 1) {
        $search.addCondition("begin_time>now()", "", "SQL")
    } else if (status == 2) {
        $search.addCondition("now() between begin_time and end_time", "", "SQL")
    } else if (status == 3 || status == "3") {
        /*已结束*/
        if (isSendResult == true) {
            $search.addCondition("result", "", "NOTNULL");
            enterLabel = "查看群面结果";
        } else {
            $search.addCondition("result", "", "NULL");
            enterLabel = "通知群面结果";
        }
        $search.addCondition("end_time<now()", "", "SQL")
    }
    $search.onSearch(function (result) {
        if (result) {
            var list = result.data.interviewList,
                $DOM = $("#" + type + "_data");
            $DOM.html("");
            for (var i = 0, len = list.length; i < len; i += 1) {
                $DOM.append($("<div>").html(constructInterviewHtml(list[i], enterLabel)));
            }
            $footer.refresh(result.data.pageNum, result.data.pageSize, result.data.totalCount);
        }
    });
    $search.doSearch(function (json) {
        handleErrorJsonResponse(json);
    });
}

function constructInterviewHtml(interview, enterLabel) {
    var html = "";
    html += "群面主题：" + interview["name"] + ",职位：<a href='<%=request.getContextPath()%>/rest/job/" + interview["jobId"] + "'>"
        + interview["job"]["name"] + "</a>,群面时间：" + interview["beginTime"]
        + "<a href='javascript:;' onclick='showUpdateInterviewDiv(" + interview["interviewId"] + ")'>修改</a>,持续时间："
        + interview["periodTime"] + "分钟,";
    html += "已申请人数：" + interview["applyUserCount"] + "---已通过人数：" + interview["passUserCount"]
        + "--已拒绝人数：" + interview["rejectUserCount"] + "--待审批人数：" + interview["pendingUserCount"];
    html += "<a href='" + wp.config.baseUrl + "/rest/interview/mvc/chat/grant/" + interview["interviewId"] + "'>" + enterLabel + "</a>";
    html += "<span id='interview_" + interview["interviewId"] + "' data='" + JSON.stringify(interview) + "' ></span>"
    return html;
}


function loadJob(type, status, isSendResult) {
    var $search = QSearch.init(wp.config.baseUrl + "/rest/job/grant/hr");
    var $footer = QFooter.init("#" + type + "_footer", function (pageNum) {
        $search.setPageNum(pageNum);
        $search.doSearch();
    });
    $search.setPageSize(1);
    if (status == 1) {
        $search.addCondition("status", status, "EQUAL")
    } else {
        $search.addCondition("status", status, "EQUAL")
    }
    $search.onSearch(function (result) {
        if (result) {
            var list = result.data.jobList;
            var $DOM = $("#" + type + "_data");
            $DOM.html("");
            for (var i = 0, len = list.length; i < len; i += 1) {
                $DOM.append($("<div>").html(constructJobHtml(list[i])));
            }
            $footer.refresh(result.data.pageNum, result.data.pageSize, result.data.totalCount);
        }
    });
    $search.doSearch(function (json) {
        handleErrorJsonResponse(json);
    });
}

function constructJobHtml(job) {
    var html = "<a href='" + wp.config.baseUrl + "/rest/job/" + job["id"] + "'>" + job["name"] + "</a>|" + param.job.jobType[job["jobType"]] + "|" + param.job.status[job["status"]] + "|" + job["place"] + "|" + job["applyUserCount"] + "|" + job["createTime"];
    if (job["latestInterview"]) {
        html += "<a href='" + wp.config.baseUrl + "/rest/interview/mvc/chat/grant/" + job["latestInterview"]["interviewId"] + "'>";
        if (job["latestInterview"]["status"] == "0") {
            html += "群面已结束，<a href='javascript:void(0);' onclick=\"showInterviewAddDiv(\'" + job["id"] + "\')\">发布新群面</a>";
        } else if (job["latestInterview"]["status"] == "1") {
            html += "群面即将进行";
        } else {
            html += "群面正在进行";
        }
        html += "</a>";
    } else if (job["status"] != 0) {
        html += "<a href='javascript:void(0);' onclick=\"showInterviewAddDiv(\'" + job["id"] + "\')\">发布新群面</a>";
    }
    if (job["status"] != 0) {
        html += "<a href='javascript:void(0);' onclick=\"closeJob(\'" + job["id"] + "\',0)\">关闭职位</a>";
        html += "<a href='javascript:void(0);' onclick=\"showUpdateJobDiv(\'" + job["id"] + "\',0)\">编辑</a>";
    }
    html += "<span id='job_" + job["id"] + "' data='" + JSON.stringify(job) + "' style='display:none'></span>";
    return html;
}

function loadEnterprise(id) {
    //alert("12");
}

/**
 *
 * @param typeName
 * @param typeId
 * @param subtypeName
 * @param subtypeId
 */
function showType(typeName, typeId, subtypeName, subtypeId) {
    $("[name='" + typeName + "']").hide();
    $("#" + typeId).show();
    $("[name='" + subtypeName + "_div']").css("color", 'black');
    $("#" + subtypeId + "_div").css("color", 'blue');
    $("[name='" + subtypeName + "']").hide();
    var $obj = $("#" + subtypeId).show();
    if (!$obj.attr("init")) {
        $obj.trigger("query");
    }
}

function showUpdateJobDiv(id) {
    if(id) {
        var job = $.parseJSON($("#job_" + id).attr("data"));
        $("[about='update_job']").each(function () {
            var $obj = $(this);
            $obj.val(job[$obj.prop("name")]);
        });
    }
    $("#list").hide();
    $("#update_job_div").show();
}

function updateJob() {
    var data = "1=1";
    $("[about='update_job']").each(function () {
        var $obj = $(this);
        data += "&" + $obj.prop("name") + "=" + $obj.val();
    });

    $.ajax({
        type: "POST",
        async: true,
        url: wp.config.baseUrl + "/rest/job/grant/hr/addOrUpdate",
        data: data,
        dataType: "json",
        cache: false,
        random: Math.random(),
        success: function (json) {
            if (handleJsonResponse(json)) {
                window.location.reload();
            }
        },
        error: function (json) {
            handleErrorJsonResponse(json);
        }
    });
}

function closeJob(jobId, status) {
    var data = "1=1&id=" + jobId + "&status=" + status;
    $.ajax({
        type: "POST",
        async: true,
        url: wp.config.baseUrl + "/rest/job/grant/hr/updateJobStatus",
        data: data,
        dataType: "json",
        cache: false,
        random: Math.random(),
        success: function (json) {
            if (handleJsonResponse(json)) {
                window.location.reload();
            }
        },
        error: function (json) {
            handleErrorJsonResponse(json);
        }
    });
}


function showInterviewAddDiv(jobId) {
//        $("#interview_list_div").hide();
    $("#add_interview_div").show();
    $("#list").hide();
    $("#update_job_div").hide();
    $("#interview_jobId").val(jobId);
    $('#interview_begin_time').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    });
}
function addInterview() {
    var viewJson = "{'jobId':'" + $("#interview_jobId").val() + "','name':'" + $("#interview_name").val() + "','periodTime':'" + $("#interview_periodTime").val() + "','status':'1',"
        + "'userMaxCount':'" + $("#interview_userMaxCount").val() + "',"
        + "'beginTime':'" + $('#interview_begin_time').datetimepicker('getFormattedDate') + "',"
        + "'resultHours':'" + $("#interview_resultHours").val() + "',"
        + "'interviewId':'" + $("#interview_id").val() + "',"
        + "'userLimit':'" + ($("#interview_isLimit").prop('checked') ? 1 : 0) + "',"
        + "'rejectMonth':'" + ($("#interview_isReject").prop('checked') ? 1 : 0) + "',"
        + "'subjectDesc':'" + $("#interview_subject").val() + "'"
        + "}";

//    var viewJson="name="+$("#name").val()+"&periodTime="+$("#periodTime").val()+"&status=1"
//            +"&userMaxCount="+$("#userMaxCount").val()+""
//            +"&beginTime="+$('#begin_time').datetimepicker('getFormattedDate')+""
//            +"&resultHours="+$("#resultHours").val()+""
//            +"&userLimit="+($("#isLimit").prop('checked')?1:0)+""
//            +"&isReject="+($("#isReject").prop('checked')?1:0)+""
//            +"";
    $.ajax({
        type: "POST",
        async: true,
        url: wp.config.baseUrl + "/rest/interview/grant/hr/addOrUpdate",
        data: "interviewJson=" + viewJson,
        dataType: "json",
        cache: false,
        random: Math.random(),
        success: function (json) {
            if (handleJsonResponse(json)) {
                window.location.reload();
            }
        },
        error: function (json) {
            handleErrorJsonResponse(json);
        }
    });
}

function showUpdateInterviewDiv(interviewId) {
    $("#update_interview_id").val(interviewId);
    var interview = $.parseJSON($("#interview_" + interviewId).attr("data"));
    $("#update_interview_begin_time").val(interview["beginTime"]);
    $("#update_interview_period_time").val(interview["periodTime"]);
    $('#update_interview_begin_time').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    });
    $('#update_interview_begin_time').datetimepicker('update', interview["beginTime"]);
    $("#update_interview_div").show();
}

function updateInterviewTime() {
    var interviewId = $('#update_interview_id').val();
    var beginTime = $('#update_interview_begin_time').datetimepicker('getFormattedDate');
    var periodTime = $('#update_interview_period_time').val();
    var data = "1=1&interviewId=" + interviewId + "&beginTime=" + beginTime + "&periodTime=" + periodTime;
    $.ajax({
        type: "POST",
        async: true,
        url: wp.config.baseUrl + "/rest/interview/grant/hr/updateTime",
        data: data,
        dataType: "json",
        cache: false,
        random: Math.random(),
        success: function (json) {
            if (handleJsonResponse(json)) {
                $("#update_interview_div").hide();
            }
        },
        error: function (json) {
            handleErrorJsonResponse(json);
        }
    });
}